<template>
  <j-modal
    :title='title'
    :width='1200'
    :visible='visible'
    :confirmLoading='confirmLoading'
    switchFullscreen
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'>
    <template slot='footer'>
      <a-button @click='handleCancel'>取消</a-button>
      <a-button @click='handleOk' type='primary' v-if='!disableSubmit'>确认</a-button>
    </template>

    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-row style='width: 100%;'>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='模版名称'>
              <a-input :disabled='disableSubmit' placeholder='请输入模版名称'
                       v-decorator="['templateName', { rules: [{ required: true, message: '请输入模版名称' }] }]" />
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='模版类型'>
              <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}"
                                 :triggerChange='true'
                                 dictCode='template_type'
                                 v-decorator="['templateType',{rules: [{ required: true, message: '请选择模版类型' }]}]"
                                 placeholder='请选择模版类型'
                                 :disabled='disableSubmit'
                                 @change="(e,v)=>changeJselect('template_type',v)"
              />
              <!--              <a-input :disabled="disableSubmit" placeholder="请输入ERP会计科目编码"-->
              <!--                       v-decorator="['erpSubjectCode']" />-->
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='关联预算科目'>
              <j-select-subjects
                v-decorator="['budgetSubjectsCode',{rules: [{ required: true, message: '请选择关联预算科目' }]}]"
                :multiple='true'
                :buttons='false'
                :disabled='disableSubmit'
                @select='(row)=>selectSubjects(row)' placeholder='请选择关联预算科目' />

              <!--              <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}"-->
              <!--                                 :triggerChange="true"-->
              <!--                                 dictCode="template_type"-->
              <!--                                 v-decorator="['budgetSubjectsCode',{rules: [{ required: true, message: '请选择关联预算科目' }]}]"-->
              <!--                                 placeholder="请选择关联预算科目"-->
              <!--                                 :disabled="disabled"-->
              <!--                                 @change="(e,v)=>changeJselect('budgetSubjectsCode',v)"-->
              <!--              />-->
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='活动发布范围'>
              <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}"
                                 :triggerChange='true'
                                 dictCode='act_scope_type'
                                 v-decorator="['actScopeType',{rules: [{ required: true, message: '请选择活动发布范围' }]}]"
                                 placeholder='请选择活动发布范围'
                                 :disabled='disableSubmit'
                                 @change="(e,v)=>changeJselect('actScopeType',v)"
              />
            </a-form-item>
          </a-col>
<!--          <a-col :md='8' :sm='24'>-->
<!--            <a-form-item-->
<!--              :labelCol='labelCol'-->
<!--              :wrapperCol='wrapperCol'-->
<!--              label='状态'>-->
<!--              <a-select :disabled='disableSubmit'-->
<!--                        v-decorator="['status',{rules: [{ required: true, message: '请选择状态' }]}]" placeholder='请选择状态'>-->
<!--                <a-select-option value=1>-->
<!--                  启用-->
<!--                </a-select-option>-->
<!--                <a-select-option value=0>-->
<!--                  禁用-->
<!--                </a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='是否采集销量数据'>
              <a-select :disabled='disableSubmit'
                        v-decorator="['isGetSales',{rules: [{ required: true, message: '是否采集销量数据' }]}]"
                        placeholder='是否采集销量数据'>
                <a-select-option :value='1'>
                  是
                </a-select-option>
                <a-select-option :value='0'>
                  否
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='8' :sm='24'>
            <a-form-item
              :labelCol='labelCol'
              :wrapperCol='wrapperCol'
              label='有效期'>
              <a-range-picker
                :disabled='disableSubmit'
                format='YYYY-MM-DD' valueFormat='YYYY-MM-DD'
                v-decorator="['date',{rules: [{ required: true, message: '请选择有效期' }]}]"
                @change='dateChange'
              />
            </a-form-item>
          </a-col>
          <a-col :md='16' :sm='24'>
            <a-form-item
              :labelCol='{
              xs: { span: 24 },
              sm: { span: 4 }
              }'
              :wrapperCol='{
              xs: { span: 24 },
              sm: { span: 14 }
              }'
              label='详细内容'>
              <a-input :disabled='disableSubmit' type='textarea' :maxLength='500' placeholder='请输入详细内容'
                       v-decorator="['remarks']" />
            </a-form-item>
          </a-col>

          <a-divider style="font-weight: 600;margin-top: 20px;" orientation="left">模板可用范围</a-divider>
          <a-col :span='24'>
            <div style="display: flex;padding:0 50px 0px 50px;margin-top: -20px">
              <div style='width: 80%;'>
                <div>
                  <div style='display: flex;margin-bottom: 12px'>
                    <j-select-org selectButtonText='新增' v-if='!disableSubmit' :inputs='false' searchIcon=''
                                  @select='orgSelect' />
                    <div style='margin-bottom: 12px'></div>
                  </div>
                  <div style='width: 70%;'>
                    <a-table
                      ref='table'
                      size='middle'
                      bordered
                      rowKey='code'
                      :columns='orgColumns'
                      :dataSource='orgList'
                      :pagination='ipagination'
                      :loading='loading'
                      @change='handleTableChange'
                    >
                      <span slot='action' v-if='!disableSubmit' slot-scope='text, record,index'>
                        <a @click.stop='orgDeleta(index)'>删除</a>
                      </span>
                    </a-table>
                  </div>
                </div>
              </div>
              <div style='width: 80%;'>
                <div>
                  <div style='display: flex;margin-bottom: 12px'>
                    <j-select-cust :value='custValue' selectButtonText='新增' v-if='!disableSubmit' :inputs='false'
                                   searchIcon='' @select='activeSelect' />
                    <div style='margin-bottom: 12px'></div>
                  </div>
                  <div style='width: 70%;'>
                    <a-table
                      ref='table'
                      size='middle'
                      bordered
                      rowKey='code'
                      :columns='custColumns'
                      :dataSource='custList'
                      :pagination='ipagination1'
                      :loading='loading'
                      @change='handleTableChange1'
                    >
                      <span slot='action' v-if='!disableSubmit' slot-scope='text, record,index'>
                        <a @click.stop='custDeleta(index)'>删除</a>
                      </span>
                    </a-table>
                  </div>
                </div>
              </div>
            </div>
          </a-col>

          <a-divider style="font-weight: 600;margin-top: 20px;" orientation="left">关联活动细类</a-divider>
          <div style='display: flex;margin-bottom: 12px;margin-left: 50px'>
              <j-select-active-class selectButtonText='添加' v-if='!disableSubmit' :inputs='false' searchIcon=''
                                     @select='classSelect'  />
          </div>
          <div style='padding:0 24px;'>
            <a-col :md='16' :sm='24'>
              <a-table
                ref='table'
                size='middle'
                bordered
                rowKey='id'
                :columns='classColumns'
                :dataSource='categoriesDetailVoList'
                :pagination='false'
                :loading='loading'
              >
                <template slot='ratio' slot-scope='t,record,index'>
                  <a-input-number v-model='t' placeholder='最低为0'
                                  :disabled='disableSubmit' :min='0' :max='100'
                                  @change="e=>tableColChange(e,'ratioLower',record,index)" style='width: 100%' />

                </template>
                <template slot='ratio1' slot-scope='t,record,index'>
                  <a-input-number v-model='t' placeholder='最高为1'
                                  :disabled='disableSubmit' :min='0' :max='100'
                                  @change="e=>tableColChange(e,'ratioUpper',record,index)" style='width: 100%' />

                </template>
                <span slot='action' v-if='!disableSubmit' slot-scope='text, record,index'>
                  <a @click.stop='classDeleta(index)'>删除</a>
                </span>
              </a-table>
            </a-col>
          </div>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction, postAction } from '@api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import JMultiSelectTag from '@comp/dict/JMultiSelectTag'
import JSelectCategories from '@comp/cn-select-popup/JSelectCategories'
import JSelectSubjects from '@comp/cn-select-popup/JSelectSubjects'
import { PageListMixin } from '@/mixins/PageListMixin'
import { ajaxGetDictItems, getDictItemsFromCache } from '@api/api'
import 'viewerjs/dist/viewer.css'
import { directive as viewer } from 'v-viewer'
import lodash from 'lodash'
import JSelectActiveColumn from '@/components/cn-select-popup/JSelectActiveColumn'
import JSelectCust from '@/components/cn-select-popup/CnSelectCust'
import JSelectOrg from '@/components/cn-select-popup/JSelectOrg'
import JSelectActiveClass from '@/components/cn-select-popup/JSelectActiveClass'


export default {
  name: 'templateModal',
  mixins: [PageListMixin],
  components: {
    JMultiSelectTag,
    JSelectCategories,
    JSelectSubjects,
    JSelectActiveColumn,
    JSelectCust,
    JSelectOrg,
    JSelectActiveClass
  },

  data() {
    return {
      title: '新增',
      disabled: false,
      taskItemsList: [],
      custList: [],
      orgList: [],
      categoriesDetailVoList: [],
      custValue: 'CUST0000000333',
      orgColumns: [
        {
          title: '组织编码',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      custColumns: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      classColumns: [
        {
          title: '活动细类编码',
          align: 'center',
          dataIndex: 'categoriesDetailCode'
        },
        {
          title: '活动细类名称',
          align: 'center',
          dataIndex: 'categoriesDetailName'
        },
        {
          title: '使用比例限制（最低）',
          align: 'center',
          dataIndex: 'ratioLower',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'ratio' }
        },
        {
          title: '使用比例限制（最高）',
          align: 'center',
          dataIndex: 'ratioUpper',
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: 'ratio1' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      disableSubmit: false,
      areaLinkage: '',
      area: '',
      province: '',
      city: '',
      modal: {},
      areaData: '',
      proName: '产品',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      url: {
        add: window._CONFIG['domianTpmURL'] + '/acttemplate/tpmActTemplate/saveOrUpdate'
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      ipagination1: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      }
    }
  },
  computed: {},
  watch: {},
  created() {

  },
  methods: {
    handleTableChange1(pagination, filters, sorter) {
      this.ipagination1 = pagination
    },
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination
    },
    tableColChange(e, key, r, index) {
      if (e instanceof Object) {
        e = e.target.value
      }
      console.log(e)
      console.log('````')
      this.categoriesDetailVoList[index][key] = e

    },

    activeSelect(row) {
      row.map(v => {
        let index = this.custList.findIndex(item => item.code == v.custCode)
        index == -1 && this.custList.push({
          dataType: '2',
          code: v.custCode,
          name: v.custName
        })
      })
    },


    orgSelect(row) {
      row.map(v => {
        let index = this.orgList.findIndex(item => item.code == v.orgCode)
        index == -1 && this.orgList.push({
          dataType: '1',
          code: v.orgCode,
          name: v.orgName
        })
      })
    },

    classSelect(row) {
      row.map(v => {
        let index = this.categoriesDetailVoList.findIndex(item => item.categoriesDetailCode == v.categoriesDetailCode)
        index == -1 && this.categoriesDetailVoList.push({
          categoriesDetailCode: v.categoriesDetailCode,
          categoriesDetailName: v.categoriesDetailName,
          ratioLower: 0,
          ratioUpper: 0
        })
      })
    },

    classDeleta(index) {
      this.categoriesDetailVoList.splice(index, 1)
    },
    custDeleta(index) {
      this.custList.splice(index, 1)
    },

    orgDeleta(index) {
      this.orgList.splice(index, 1)
    },

    add() {
      this.edit({})
    }
    ,
    edit(record) {
      this.form.resetFields()
      this.custList = []
      this.orgList = []
      this.categoriesDetailVoList = []
      this.model = Object.assign({}, record)
      // if(this.model.status == 1){
      //   this.model.status = '启用'
      // }else if(this.model.status == 0) {
      //   this.model.status = '禁用'
      // }
      this.visible = true
      if (record.id) {
        this.$nextTick(() => {
          console.log(this.model.status)
          let arry = this.model.subjectVoList.map(v => v.budgetSubjectsName)
          this.model.date = [this.model.startDate, this.model.endDate]
          this.categoriesDetailVoList = this.model.categoriesDetailVoList
          this.model.budgetSubjectsCode = arry + ''
          this.custList = this.model.scopeVoList.filter(v => v.dataType == 2)
          this.orgList = this.model.scopeVoList.filter(v => v.dataType == 1)
          this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
          // this.$set(this, 'taskItemsList', record.execRequires)
          // this.$set(this, 'taskItemsList1', record.writeOffRequires)
        })
      } else {

      }
    },
    close() {
      this.confirmLoading = false
      this.visible = false
    }
    ,
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = { ...this.model, ...values }
          formData.scopeVoList = [...this.custList, ...this.orgList]
          formData.categoriesDetailVoList = this.categoriesDetailVoList
          postAction(this.url.add, formData).then(res => {
            if (res.success) {
              that.$message.success(res.message)
              that.close()
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    }
    ,
    handleCancel() {
      this.close()
    }
    ,
    changeJselect(name, value) {
      console.log(value)
      name = name.split('Code')
      if (name.length > 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        this.model[name] = value
        console.log(this.model)
      }
    },
    dateChange(date) {
      if (!date) {
        this.model.startDate = ''
        this.model.endDate = ''
        return
      }
      this.model.startDate = date[0]
      this.model.endDate = date[1]
    },


    selectSubjects(row, name, key) {
      let subjectVoList = []
      let list = []
      row.map(v => {
        subjectVoList.push({
          budgetSubjectsCode: v.subjectsCode,
          budgetSubjectsName: v.subjectsName
        })
        list.push(v.subjectsName)
      })
      this.model.budgetSubjectsName = list + ''
      this.model.subjectVoList = subjectVoList
    },


    selectRole(row, name, key) {
      console.log(row)
      let value = row.map(v => v[key])
      name = name.split('Code')
      if (name.length >= 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        this.model[name] = value + ''
      }
    }
  }
}
</script>

<style lang='less' scoped>
.items-title {
  padding: 12px 24px;
  margin: 12px 0;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #e8e8e8;
  border-top: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
}


.ant-transfer {
  width: 100%;
  display: flex !important;
  align-items: center;
}

.ant-transfer-operation {
  display: flex !important;
  flex-direction: column !important;
  align-items: center;
}

.file-box {
  position: relative;
  opacity: 1;
}

.file-btn {
  width: 100%;
  opacity: 0;
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  height: 100%;
}

.tableImages {
  width: 100%;
  opacity: 0;
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  height: 100%;
}

.areaAdd {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .areaAdd-one {
    width: 40%;
    display: flex;
    flex-direction: column;
  }

  .areaAdd-mutiple {
    border: 1px solid black;
    width: 100%;
    min-height: 200px;
  }

  .contain-text {
    font-weight: 700;
    font-size: 18px;
  }
}

/deep/ .ant-modal-body {
  padding: 24px 0px;
}

/deep/ .ant-tabs-bar {
  padding-left: 24px;
}
</style>